package dc.com.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B><BR>
 * <B>概要说明：过滤头字段参数信息，并将信息装进集合中,在将集合中的头字段设置给httpresponse</B><BR>
 * @author zhangl（D）
 * @since 2017年8月3日
 */
public class GzipFilter implements Filter {
	/** 参数键值：头信息 */
	public static final String PARAM_KEY_HEADERS = "headers";
	
	/** 头信息 */
	private Map<String,String> headers;
	
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String param = filterConfig.getInitParameter(PARAM_KEY_HEADERS);
		if(param == null || param.trim().length() < 1) {
			return;
		}
		this.headers = new HashMap<String, String>();
		String[] params = param.split(",");
		String[] kvs = null;
		for(int i = 0; i < params.length; i++) {
			param = params[i];
			if(param != null && param.trim().length() > 0) {
				kvs = param.split("=");
				if(kvs != null && kvs.length == 2) {
					headers.put(kvs[0], kvs[1]);
				}
			}
		}
		if(headers.isEmpty()) {
			this.headers = null;
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if(this.headers != null) {
			HttpServletResponse hsr = (HttpServletResponse) response;
			for(Entry<String,String> entry : headers.entrySet()) {
				hsr.addHeader(entry.getKey(), entry.getValue());
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		this.headers.clear();
		this.headers = null;
	}
}
